import functools

from flask import Flask, render_template, jsonify, redirect, request, session, g
from datetime import datetime
from util import overview_data, grade_city_data, asymptomatic_province_data, utils
from flask_sqlalchemy import SQLAlchemy
# 导入管理蓝图
from manager import managerapi, covapi
import config
from models import db, UserInfo
from factory import create_app

app = create_app()

app = Flask(__name__)
app.register_blueprint(managerapi.bg)
app.register_blueprint(covapi.cov)
app.config.from_object(config)
db = SQLAlchemy(app)
app.config['SECRET_KEY'] = 'a'


# 装饰器验证用户登录
def required_login(view_fun):
    @functools.wraps(view_fun)
    def fun1(*args, **kwargs):
        if 'username' not in session:
            return redirect('/tologin')
        g.User = UserInfo.query.get(session['id_card'])
        return view_fun(*args, **kwargs)

    return fun1


@app.route('/')
def show():
    id_card = session.get('id_card')
    username = session.get('username')

    china_overview_data = overview_data.get_overview_data()
    china_add_overview_data = overview_data.get_china_day_add_list()
    grade_city_data_list = grade_city_data.get_china_grade_city_data()

    # 全国城市疫情个数
    china_city_statis = overview_data.get_china_city_statis()

    # 现有无症状感染者
    now_asy_data = asymptomatic_province_data.get_asymptomatic_province()
    # 新增无症状感染者
    add_asy_data = asymptomatic_province_data.get_asymptomatic_add_province()

    return render_template('index.html', china_overview_data=china_overview_data,
                           china_add_overview_data=china_add_overview_data, china_city_statis=china_city_statis,
                           grade_city_data_list=grade_city_data_list,
                           now_asy_data=now_asy_data, add_asy_data=add_asy_data, username=username,
                           id_card=id_card)


# 获取全国各省疫情概况地图
@app.route('/c2')
def get_c2_data():
    res = []
    for tup in utils.get_c2_data():
        res.append({"name": tup[0], "value": int(tup[1])})
    return jsonify({"data": res})


# 获取安徽各市疫情概况地图
@app.route('/anhuiMap')
def get_anhuiMap():
    res = []
    anhui_data = utils.get_anhui_data()
    for tup in anhui_data:
        res.append({"name": tup[0], "value": int(tup[1])})
    print(res)
    return jsonify({"data": res})


# 获取安徽各市疫情概况地图
@app.route('/anhui')
def toanhuiPage():
    id_card = session.get('id_card')
    username = session.get('username')
    return render_template("anhuiData.html", username=username,
                           id_card=id_card)


# 新闻list
@app.route('/hotNews')
def hotNews():
    listNews = utils.getHotNews()
    listNewsJson = jsonify(listNews).json
    id_card = session.get('id_card')
    username = session.get('username')
    return render_template("hotNews.html", list=listNewsJson, username=username,
                           id_card=id_card)



@app.route('/tologin')
def tologin():
    return render_template("login.html")


@app.route('/towxlogin')
def towxlogin():
    return render_template("loginWX.html")


@app.route('/toregister')
def toregister():
    return render_template("register.html")


@app.route('/logout')
def logout():
    session.clear()
    return redirect("/")


@app.route('/login', methods=['POST'])
def login():
    id_card_phone = request.values.get("id_card_phone")
    password = request.values.get("password")

    user1 = UserInfo.query.filter_by(user_name=id_card_phone).first()
    user2 = UserInfo.query.filter_by(mobile=id_card_phone).first()
    user3 = UserInfo.query.filter_by(id_card=id_card_phone).first()
    user = None

    if user1 is not None:
        user = user1

    if user2 is not None:
        user = user2

    if user3 is not None:
        user = user3

    if user:
        if user.pwd == password:
            # 记录用户登录
            now = datetime.now()
            session['user_id'] = user.id
            session['username'] = user.user_name
            session['id_card'] = user.id_card
            session['phone'] = user.mobile
            user.update_time = now
            db.session.commit()
            # 返回头像和昵称
            return jsonify(result=200)
        else:
            return jsonify(result=400)  # 密码错误
    else:
        return jsonify(result=400)  # 密码错误


@app.route('/register', methods=['POST'])
def register():
    username = request.values.get("username")
    idcard = request.values.get("idcard")
    phone = request.values.get("phone")
    password = request.values.get("password")
    mobile_exists = UserInfo.query.filter_by(mobile=phone).count()

    if mobile_exists:
        return jsonify(result=300)  # 手机号存在

    user = UserInfo()
    user.user_name = username
    user.id_card = idcard
    user.mobile = phone
    user.pwd = password
    db.session.add(user)
    db.session.commit()
    return jsonify(result=200)  # 成功


if __name__ == '__main__':
    # db.init_app(app)
    # session(app)
    # app.jinja_env.auto_reload = True
    app.run(debug=True)
